<?php
// $Id$

/**
 * Controller_Internationally 控制器
 */
class Controller_Internationally extends Controller_Prepare
{
    /**
     * 国际交流信息
     */
    public function actionIndex()
    {
        // Error handling 初步过滤获得的值，必须满足值类型
        $Gnews_id  = isset($_GET['news_id'])  && is_numeric($_GET['news_id'])  ? $_GET['news_id']  : NULL;
        $Gctgry_id = isset($_GET['ctgry_id']) && is_numeric($_GET['ctgry_id']) ? $_GET['ctgry_id'] : NULL;
        $Gtag      = isset($_GET['tag']) ? $_GET['tag'] : NULL;
        
        /** 
         * 获取当前显示的新闻
         *
         * @var object $currentNews
         */
        $currentnews = NULL;
        if(isset($Gctgry_id))
        {
            $currentNews = News::find(NewsCategory::genCondition($Gctgry_id))->order(Q::ini('appini/sort'))->query();
        }
        elseif(isset($Gnews_id))
        {
            $currentNews = News::find('news_id = ?', $Gnews_id)->query();
        }
        elseif(CIB::_SQL_filter($Gtag))
        {
            $currentNews = News::find('tag like ? AND category_id = 82', "%,{$Gtag},%")->order(Q::ini('appini/sort'))->query();
        }
        else
        {
            $currentNews = NULL;
        }

        // Error handling 如果恶意输入不存在的 ctgry_id 或 news_id，导致当前新闻不存在，则显示最新一条新闻
        // Error handling 检查 news_id
        if($currentNews && $currentNews->title == '')
        {
            $currentNews = NULL;
        }
        
      /**
         * 更新当前新闻"阅读"值 hasread = hasread + 1
         */
        if($currentNews)
        {
            News::meta()->updateDbWhere(new QDB_Expr('hasread = hasread + 1'), 'news_id = ?', $currentNews->news_id);
        }

        /**
         * 处理标签搜索结果：$tag
         *
         * @var array $tagRecords
         */
        $tagRecords = array();
        if(CIB::_SQL_filter($Gtag))
        {
            $tagRecords = News::find('tag like ? AND category_id = 82', "%,{$Gtag},%")
                ->all()->order(Q::ini('appini/sort'))->query();
            
            // 更新 hit_as_query 字段
            $t = Tag::find('category = ? AND tag = ?', '国际交流', $Gtag)->query();
            if($t->tag != '')
            {
                $t->hit_as_query += 1;
                $t->save();
            }
        }

        /**
         * CSS HIGHLIGHT
         *
         * @var string $css
         */
        $css = '';
        if($currentNews)
        {
            $css = "a[href*='_{$currentNews->news_id}.html']".HIGHLIGHT_CSS;
        }

        $this->_view['currentNews'] = $currentNews;
        $this->_view['css']         = $css;
        $this->_view['tagRecords']  = $tagRecords;
    }
}